<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">名称搜索:</span>
                        <el-input
                            v-model="searchForm.search"
                            size="small"
                            style="width: 130px;"
                            placeholder="请输入id/手机号"
                        />
                    </div>
                    <div style="display: flex; align-items: center; ">
                        <span>审核状态:</span>
                        <el-select v-model="searchForm.state" size="small" style="margin-left: 10px; flex: 1;width: 150px;">
                            <el-option label="未审核" value="0"></el-option>
                            <el-option label="已审核" value="1"></el-option>
                            <el-option label="已驳回" value="2"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            size="small"
                            v-model="searchForm.start_time"
                            type="date"
                            style="width: 150px;"
                            placeholder="开始日期">
                        </el-date-picker>
                        <span style="margin: 0 5px;">至</span>
                        <el-date-picker
                            size="small"
                            style="width: 150px;"
                            v-model="searchForm.end_time"
                            type="date"
                            placeholder="结束日期">
                        </el-date-picker>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                    <el-button type="success" size="small" style="margin-left: 10px;" @click="handleReset">重置</el-button>
                </div>
            </div>
            <el-table :data="tableData" height="560" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" label="用户ID"  align="center" />
                <el-table-column prop="username" label="用户名"  align="center" />
                <el-table-column prop="username" label="身份证正面"  align="center">
                    <template slot-scope="scope">
                        <img
                            style="width: 50px;height: 50px"
                            :src="$appConfig.baseUrl + scope.row.front_card"
                            @click="openCertificateDialog(scope.row.front_card)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="身份证反面"  align="center">
                    <template slot-scope="scope">
                        <img
                            style="width: 50px;height: 50px"
                            :src="$appConfig.baseUrl + scope.row.reverse_card"
                            @click="openCertificateDialog1(scope.row.reverse_card)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="idcard_name" label="姓名" align="center" />
                <el-table-column prop="sex" label="性别" align="center" />
                <el-table-column prop="idcard" label="身份证号" align="center" />
                <el-table-column prop="create_time" label="上传时间" align="center" />
                <el-table-column prop="exam_time" align="center" label="审核时间" width="160">
                    <template slot-scope="scope">
                        <span v-if="scope.row.card_state > 0">
                          {{ formatTime(scope.row.exam_time) }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="card_state" label="审核状态">
                    <template slot-scope="scope">
                    <span :style="{ color: getStatusColor(scope.row.card_state) }">
                        {{ scope.row.card_state === 0 ? '未审核' : scope.row.card_state === 1 ? '已审核' : scope.row.card_state === 2 ? '已驳回' : '未知状态' }}
                    </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleAudit(scope.row)">审核</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total"
            />
        </div>

        <!-- 审核对话框 -->
        <el-dialog title="实名认证审核" :visible.sync="auditDialogVisible" width="600px" :close-on-click-modal="false">
            <div v-if="currentRecord" class="audit-content">
                <div class="info-item">
                    <span class="label">用户ID7787：</span>
                    <span>{{ currentRecord.id }}</span>
                </div>
                <div class="info-item">
                    <span class="label">用户名：</span>
                    <span>{{ currentRecord.username }}</span>
                </div>
                <div class="info-item">
                    <span class="label">身份证正面：</span>
                    <img :src="imageUrl + currentRecord.front_card" class="id-card-image" @click="openImagePreview(imageUrl + currentRecord.front_card)" />
                </div>
                <div class="info-item">
                    <span class="label">身份证反面：</span>
                    <img :src="imageUrl + currentRecord.reverse_card" class="id-card-image" @click="openImagePreview(imageUrl + currentRecord.reverse_card)" />
                </div>
                <div style="display: flex">
                    <div>备注:</div>
                    <el-input type="textarea" style="width: 80%;margin-left: 66px;" v-model="remark"/>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="auditDialogVisible = false" size="small">取消</el-button>
                <el-button type="danger" @click="handleReject" size="small">驳回</el-button>
                <el-button type="primary" @click="handleApprove" size="small">通过</el-button>
            </div>
        </el-dialog>

        <!-- 申请凭证大弹窗 -->
        <el-dialog title="身份证正面" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="true">
            <div style="text-align: center;">
                <img :src="currentQRCode" style="max-width: 100%; max-height: 800px;">
            </div>
        </el-dialog>

        <el-dialog title="身份证反面" :visible.sync="qrCodeDialogVisible1" width="300px" :close-on-click-modal="true">
            <div style="text-align: center;">
                <img :src="currentQRCode" style="max-width: 100%; max-height: 800px;">
            </div>
        </el-dialog>

        <!-- 图片预览对话框 -->
        <el-dialog title="图片预览" :visible.sync="imagePreviewVisible" width="800px" :close-on-click-modal="true">
            <img :src="currentPreviewImage" class="preview-image" />
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            searchForm: {
                state:"",
                end_time: '',
                start_time: '',
                search: '',
            },
            imageUrl:this.$appConfig.baseUrl,
            // imageUrl:"http://www.ts.com/",
            tableData: [],
            currentPage: 1,
            qrCodeDialogVisible:false,
            qrCodeDialogVisible1:false,
            remark:"",
            pageSize: 15,
            total: 0,
            auditDialogVisible: false,
            currentRecord: null,
            imagePreviewVisible: false,
            currentPreviewImage: '',
            shenId:null
        }
    },
    created() {
        this.fetchAdminList()
    },
    methods: {  formatTime(timestamp) {
            if (!timestamp || timestamp === 0) return '-';

            const date = new Date(timestamp * 1000); // 秒级时间戳转毫秒
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        openCertificateDialog(thumb) {
            this.currentQRCode = this.$appConfig.baseUrl + thumb;
            this.qrCodeDialogVisible = true;
        },
        openCertificateDialog1(thumb) {
            this.currentQRCode = this.$appConfig.baseUrl + thumb;
            this.qrCodeDialogVisible1 = true;
        },
        getStatusColor(state) {
            // 0和2都返回红色，1返回绿色
            if (state === 0 || state === 2) {
                return 'red';
            } else if (state === 1) {
                return 'green';
            }
            return 'black';
        },
        fetchAdminList(params = {}) {
            const defaultParams = {
                is_test:1,
                page: this.currentPage,
                ...params
            };
            this.$message.info({
                message: '正在加载数据...',
                duration: 0,
                showClose: true,
                iconClass: 'el-icon-loading'
            });
            this.$http.get('/admin/UserInfo/lists', {params: defaultParams}).then(result => {
                if (result.code === 200) {
                    this.tableData = result.data.data || [];
                    this.total = parseInt(result.data.total) || 0;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取列表数据失败，请重试');
            }).finally(() => {
                this.$message.closeAll();
            });
        },
        handleSearch() {
            const formatDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                const timestamp = new Date(formattedDate).getTime();
                return Math.floor(timestamp / 1000); // 转换为秒级时间戳
            };

            this.searchParams = {
                ...this.searchForm,
                start_time: formatDate(this.searchForm.start_time),
                end_time: formatDate(this.searchForm.end_time)
            };
            // Remove empty string properties from searchParams before sending
            Object.keys(this.searchParams).forEach(key => {
                if (this.searchParams[key] === '') {
                    delete this.searchParams[key];
                }
            });
            this.currentPage = 1;
            this.fetchAdminList(this.searchParams);
        },
        handleReset() {
            this.searchForm = {
                date: '',
                search: '',
            }
            this.fetchAdminList()
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.fetchAdminList()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.fetchAdminList()
        },
        handleAudit(row) {
            this.shenId = row.id
            this.currentRecord = row
            this.remark = row.remark
            this.auditDialogVisible = true
        },
        handleApprove() {
            this.$confirm('确认通过该用户的实名认证吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const data = {
                    id:this.shenId,
                    state:1
                }
                this.$http.post('/admin/UserInfo/emUserInfo',data).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.auditDialogVisible = false
                        this.fetchAdminList()
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            }).catch(() => {})
        },
        handleReject() {
            this.$confirm('确认驳回该用户的实名认证吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const data = {
                    id:this.shenId,
                    state:2,
                    remark:this.remark
                }
                if(this.remark === ""){
                    this.$message.error("请输入驳回原因");
                }else{
                    this.$http.post('/admin/UserInfo/emUserInfo',data).then(result => {
                        if (result.code === 200) {
                            this.$message.success(result.msg);
                            this.auditDialogVisible = false
                            this.fetchAdminList()
                        } else {
                            this.$message.error(result.msg);
                        }
                    });
                }


            }).catch(() => {})
        },
        openImagePreview(imageUrl) {
            this.currentPreviewImage = imageUrl;
            this.imagePreviewVisible = true;
        },
        previewImage(imageUrl) {
            // Implement additional image preview logic here if needed
            console.log('Previewing image:', imageUrl)
        }
    }
}
</script>

<style scoped lang="less">
.admin-page {
    padding: 20px;

    .search-label {
        margin-right: 10px;
        color: #606266;
    }

    .el-table {
        margin-top: 20px;
    }

    .el-pagination {
        margin-top: 20px;
        text-align: right;
    }

    .audit-content {
        .info-item {
            margin-bottom: 20px;
            display: flex;
            align-items: center;

            .label {
                width: 100px;
                color: #606266;
            }

            .id-card-image {
                width: 200px;
                height: 120px;
                object-fit: cover;
                cursor: pointer;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                transition: all 0.3s;

                &:hover {
                    transform: scale(1.05);
                }
            }
        }
    }
}
/deep/ .el-dialog{
    overflow: hidden;
}


/deep/ .el-dialog__header{
    text-align: center;
    margin-top: 15px;
}
.el-pagination {
    margin-top: 24px;
    padding: 12px 0;
    text-align: right;

    :deep(.el-pagination__total) {
        margin-right: 12px;
    }

    :deep(.btn-prev),
    :deep(.btn-next) {
        border-radius: 4px;
        background-color: #fff;
    }

    :deep(.el-pager li) {
        border-radius: 4px;
        background-color: #fff;

        &.active {
            background-color: #2563eb;
        }
    }
}

.id-card-image {
    width: 200px;
    height: auto;
    cursor: pointer;
}

.preview-image {
    max-width: 100%;
    max-height: 600px;
}
</style>
